<template>
  <div class="chat-container">
    <!-- 左侧讨论组列表 -->
    <div class="groups-sidebar">
      <div class="sidebar-header">
        <div class="sidebar-title">
          <el-icon><ChatLineRound /></el-icon>
          讨论小组
        </div>
      </div>
      <div class="groups-list">
        <div
          v-for="group in discussionGroups"
          :key="group.id"
          :class="['group-item', { active: currentGroup.id === group.id }]"
          @click="selectGroup(group)"
        >
          <div
            class="group-avatar"
            :style="{ backgroundColor: '#4b6cb7' }"
          >
            {{ group.name.charAt(0) }}
          </div>
          <div class="group-info">
            <div class="group-name">{{ group.name }}</div>
            <div class="group-lastmsg">老师：{{ group.user_id.name }}</div>
            <div class="group-badge">班级ID：{{group.extral_2}}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main">
      <div class="chat-header">
        <div class="current-group">
          <div
            class="group-avatar"
            :style="{ backgroundColor: '#4b6cb7' }"
          >
            {{ currentGroup && currentGroup.name ? currentGroup.name.charAt(0) : '?' }}
          </div>
          <div>
            <div class="group-name">{{ currentGroup?.name || '' }}</div>
            <div class="group-members" v-if="numCourse.length > 0">
              班级人数：{{ numCourse.length }}人
            </div>
          </div>
        </div>
        <div class="header-actions">
          <el-tooltip content="搜索消息" placement="top">
            <el-button circle>
              <el-icon><Search /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="成员列表" placement="top">
            <el-button circle>
              <el-icon><User /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="设置" placement="top">
            <el-button circle>
              <el-icon><Setting /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in Message" :key="index">
          <!-- 消息内容 -->
          <div :class="['message-item', { self: isSelfMessage(message) }]">
            <div class="message-content">
              <div class="message-sender">{{ message.user_id.name }}</div>
               <!-- 判断是否为图片消息 -->
              <div v-if="message.is_image" class="message-bubble image-message">
                <img
                  :src="message.image_url"
                  alt="图片消息"
                  class="message-image"
                  @click="previewImage(message.image_url)"
                />
              </div>
              <!-- 普通文本消息 -->
              <div v-else class="message-bubble">{{ message.content }}</div>
              <div class="message-time">{{ message.send_time }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input">
        <div class="input-actions">
          <div class="action-button" @click="handleAddImage">
            <el-icon><Picture /></el-icon>
            <!-- 隐藏的文件输入框 -->
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              class="hidden"
              @change="handleFileChange"
            />
          </div>
          <div class="action-button" @click="handleAddFile">
            <el-icon><FolderAdd /></el-icon>
          </div>
          <div class="action-button" @click="toggleVoiceInput">
            <el-icon><Microphone /></el-icon>
          </div>
        </div>
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息..."
          resize="none"
          @keydown.enter.prevent="sendMessage"
        ></el-input>
        <el-button type="primary" class="send-button" @click="sendMessage" :loading="sending">
          发送 <el-icon><Position /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import {
  ElIcon,
  ElButton,
  ElInput,
  ElBadge,
  ElTooltip,
  ElMessage,
  ElImageViewer
} from 'element-plus'
import {
  ChatLineRound,
  Search,
  User,
  Setting,
  Picture,
  FolderAdd,
  Microphone,
  Position
} from '@element-plus/icons-vue'
import http from "@/util/request";
const sending = ref(false)
const Loading = ref(false)
const discussionGroups = ref([])
const userinfo = ref([])
const userID = ref([])
// 班级成员
const numCourse = ref([])
// 当前选中的讨论组
const currentGroup = ref(null)
// 获取文件输入框的引用
const fileInput = ref(null);
// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await http.get(`/api/get_user_id/${userinfo.value.username}/`)
    userID.value = res.data
    console.log(userID.value[0]['id'])
  }catch (error){
    console.error('获取数据失败:', {
      request: error.config.data, // 请求数据
      response: error.response?.data, // 服务器返回的错误信息
      status: error.response?.status, // HTTP 状态码
    })
  }
}
// 获取自己拥有的课程
const getMyCourseList = async () => {
  try {
    Loading.value = true
    const res = await http.get(`/api/my_stu_course/${userID.value[0]['id']}`)
    discussionGroups.value = res.data
    console.log(discussionGroups.value)
    // console.log(discussionGroups.value[0])
    if (discussionGroups.value.length > 0) {
      selectGroup(discussionGroups.value[0])
    }
  }catch (error){
    console.error('获取数据失败:', {
      request: error.config.data, // 请求数据
      response: error.response?.data, // 服务器返回的错误信息
      status: error.response?.status, // HTTP 状态码
      headers: error.config.headers,
    })
    ElMessage.error('修改数据失败')
  }finally {
    Loading.value = false
  }
}

// 讨论组数据
const Message = ref([])
// 新消息
const newMessage = ref('')

// 消息容器引用
const messagesContainer = ref(null)
// 在script setup中添加WebSocket相关变量
const socket = ref(null);
const isConnected = ref(false);
const reconnectTimer = ref(null);
// 初始化WebSocket连接
const initWebSocket = () => {
  // 关闭已有连接
  if (socket.value) {
    socket.value.close();
  }

  // WebSocket连接地址（替换为你的后端WebSocket地址）
  // 建议包含用户ID和当前课程ID用于身份验证和消息路由
  const ID = userID.value[0]['id'];
  const courseId = currentGroup.value?.extral_2 || '';
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  // 如果在其他电脑运行后端，则需要更改这里的IP地址
  const wsUrl = `${wsProtocol}//127.0.0.1:8000/api/ws/${ID}/${courseId}`;
  console.log(wsUrl)

  // 创建WebSocket实例
  socket.value = new WebSocket(wsUrl);

  // 连接成功
  socket.value.onopen = () => {
    console.log('WebSocket连接成功');
    isConnected.value = true;
    // 清除重连计时器
    if (reconnectTimer.value) {
      clearTimeout(reconnectTimer.value);
    }
  };

  // 接收消息
  socket.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      handleReceivedMessage(message);
    } catch (error) {
      console.error('解析WebSocket消息失败:', error);
    }
  };

  // 连接关闭
  socket.value.onclose = (event) => {
    console.log('WebSocket连接关闭，代码:', event.code);
    isConnected.value = false;
    // 自动重连（非正常关闭情况下）
    if (event.code !== 1000) {
      reconnectWebSocket();
    }
  };

  // 连接错误
  socket.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
    isConnected.value = false;
  };
};
// 处理收到的消息
const handleReceivedMessage = (message) => {
  console.log(message)
  // 检查消息是否属于当前选中的讨论组
  if (message.extral_2 === currentGroup.value?.extral_2) {
    // 添加到消息列表
    Message.value.push(message);
    // 滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 重连机制
const reconnectWebSocket = () => {
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value);
  }
  // 5秒后尝试重连
  reconnectTimer.value = setTimeout(() => {
    console.log('尝试重连WebSocket...');
    initWebSocket();
  }, 5000);
};

// 通过WebSocket发送消息
const sendMessageViaWebSocket = (messageObj) => {
  if (isConnected.value && socket.value) {
    try {
      socket.value.send(JSON.stringify(messageObj));
      return true;
    } catch (error) {
      console.error('WebSocket发送消息失败:', error);
      return false;
    }
  } else {
    console.warn('WebSocket未连接，无法发送消息');
    return false;
  }
};
// 发送消息
const sendMessage = async () => {
  // 检查消息是否为空或正在发送
  if (!newMessage.value.trim() || sending.value) return
  sending.value = true
  try {
    const now = new Date()
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    // 构造包含日期和时间的字符串
    const time = `${year}-${month}-${day} ${hours}:${minutes}`;
    // 构造消息对象
    const newMessageObj = {
      content: newMessage.value,
      send_time: time,
      extral_2: currentGroup.value.extral_2,
      user_id: {
        id: userID.value[0].id,
        name: userID.value[0].name
      }
    };

    // 尝试通过WebSocket发送
    const wsSent = sendMessageViaWebSocket(newMessageObj);
    // 如果WebSocket发送失败，降级使用HTTP
    if (!wsSent) {
      const res = await http.post(`/api/add_stu_course_message`, {
        content: newMessage.value,
        send_time: time,
        extral_2: currentGroup.value.extral_2,
        user_id_id: userID.value[0].id,
      });

      if (res.data.code !== 200) {
        ElMessage.error('发送失败');
        return;
      }
    }

    // 发送成功，更新本地消息列表
    ElMessage.success('发送成功');
    newMessage.value = '';

    // 滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  }catch (error) {
  console.error('发送数据失败:', {
    // 先检查config是否存在，再访问data
    request: error.config ? error.config.data : '无请求配置',
    // 先检查response是否存在，再访问data
    response: error.response ? error.response.data : '无响应数据',
    status: error.response ? error.response.status : '无状态码',
  })
  // 可以在这里添加用户提示
  ElMessage.error('发送失败，请检查网络连接')
  }finally {
    sending.value = false
  }
}
// 选择讨论组
const selectGroup = async (group) => {
  currentGroup.value = group
  console.log(currentGroup.value.extral_2)
  // 在实际应用中，这里会加载该讨论组的消息
  try {
    Loading.value = true
    const res = await http.get(`/api/get_stu_course_message/${currentGroup.value.extral_2}/`)
    Message.value = res.data
    console.log(Message.value)
    const num = await http.get(`/api/get_stu_course_num/${currentGroup.value.extral_2}/`)
    numCourse.value = num.data
    // console.log(numCourse.value)
    // 切换讨论组后重新连接WebSocket
    initWebSocket();
    }catch (error){
      console.error('获取数据失败:', {
        request: error.config.data, // 请求数据
        response: error.response?.data, // 服务器返回的错误信息
      })
    }
  ElMessage.success(`已切换到 ${group.name}`)
  nextTick(() => {
    scrollToBottom()
  })
}
const isSelfMessage = (message) => {
  if (!userID.value || userID.value.length === 0 || !userID.value[0]) return false;
  return message.user_id.id === userID.value[0].id;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
  })
}

// 处理图片添加
const handleAddImage = () => {
  fileInput.value.click();
}
// 处理选择的文件
const handleFileChange = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    // 清空选择，避免重复处理同一文件
    e.target.value = '';
    return;
  }

  // 验证文件大小（示例：限制5MB以内）
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    ElMessage.error('图片大小不能超过5MB');
    e.target.value = '';
    return;
  }

  // 处理图片文件
  ElMessage.success(`已选择图片: ${file.name}`);
  console.log(file)
   // 上传图片到服务器
  await uploadImage(file);
  // 清空选择，允许重复选择同一文件
  e.target.value = '';
};
const uploadImage = async (file) => {
  try {
    const formData = new FormData();
    const now = new Date()
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    // 构造包含日期和时间的字符串
    const time = `${year}-${month}-${day} ${hours}:${minutes}`;
    formData.append('content', file);
    formData.append('send_time', time);
    formData.append('extral_2', currentGroup.value.extral_2);
    formData.append('user_id_id', userID.value[0].id);
    const res = await http.fileUpload('/api/upload_image', formData)
  }catch (error){
    console.error('上传图片失败:', {
      request: error.config.data, // 请求数据
      response: error.response?.data, // 响应数据
      status: error.response?.status, // 状态码
    })
  }
}
// 图片预览功能
const previewImage = (imageUrl) => {
  ElImageViewer({
    urlList: [imageUrl]
  })
}
// 处理文件添加
const handleAddFile = () => {
  ElMessage.info('文件添加功能')
}

// 切换语音输入
const toggleVoiceInput = () => {
  ElMessage.info('语音输入功能')
}

// 组件挂载后滚动到底部
onMounted(async () => {
  userinfo.value = JSON.parse(localStorage.getItem('userinfo'))
  await getUserInfo()
  await getMyCourseList()
  scrollToBottom()
  // 初始加载完成后连接WebSocket
  if (currentGroup.value) {
    initWebSocket();
  }
})
// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (socket.value) {
    socket.value.close(1000, '组件卸载');
  }
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value);
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Helvetica Neue', Helvetica, Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 左侧边栏 - 讨论组列表 */
.groups-sidebar {
  width: 280px;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  color: white;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.groups-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.group-item {
  padding: 14px 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.group-item:hover {
  background-color: #f5f7fa;
}

.group-item.active {
  background-color: #ecf5ff;
  border-right: 3px solid #409eff;
}

.group-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 16px;
}

.group-info {
  flex: 1;
  min-width: 0;
}

.group-name {
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.group-lastmsg {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.group-badge {
  display: inline-block;
  padding: 2px 6px;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  font-size: 12px;
}

/* 主聊天区域 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.current-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.group-members {
  font-size: 13px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f9fafc;
}

.message-date {
  text-align: center;
  margin: 10px 0;
  color: #909399;
  font-size: 12px;
}

.message-item {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message-item.self {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  flex-shrink: 0;
  object-fit: cover;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  word-break: break-word;
}

.message-item .message-bubble {
  background: white;
  border-top-left-radius: 4px;
}

.message-item.self .message-bubble {
  background: #409eff;
  color: white;
  border-top-right-radius: 4px;
}

.message-sender {
  font-weight: 600;
  font-size: 14px;
  color: #606266;
}

.message-item.self .message-sender {
  text-align: right;
  color: #409eff;
}

.message-time {
  font-size: 12px;
  color: #c0c4cc;
}

.message-item.self .message-time {
  text-align: right;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.input-actions {
  display: flex;
  gap: 10px;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f5f7fa;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.action-button:hover {
  background: #409eff;
  color: white;
}

.send-button {
  align-self: flex-end;
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
  }

  .groups-sidebar {
    width: 100%;
    height: 200px;
  }

  .message-item {
    max-width: 90%;
  }
}
.image-message {
  padding: 0;
  background: transparent;
  border: none;
  box-shadow: none;
  max-width: 300px;
}

.message-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 10px;
  cursor: pointer;
  object-fit: cover;
}

.message-image:hover {
  opacity: 0.9;
}
.hidden {
  display: none;
}
</style>
